/*Copyright Tom Lukeywood 2015
    This file is part of ASCII To BrainF**ck Converter.

    ASCII To BrainF**ck Converter is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    ASCII To BrainF**ck Converter is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with ASCII To BrainF**ck Converter.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]);

int main(int argc, char *argv[]){

FILE *fp = fopen(argv[1], "r");
unsigned long int counter;
unsigned long int counter2;
unsigned long int counter3;
unsigned long int file_size;
signed char* pstr = NULL;

if (argc != 2){printf("usage: %s file.txt\n",argv[0]);exit(0);}

/*get the size of the file if there is one*/
if(fp != NULL){
fseek(fp, 0, SEEK_END);
file_size = ftell(fp);
fseek(fp, 0, SEEK_SET);
}
printf("Allocating Memory %ld Bytes\n", file_size);
pstr = (char *)malloc(file_size * sizeof(char));

//check if out of memory
if(pstr == 0){
printf("%s: fatal error: out of memory :(\n", argv[0]);
exit(0);
}

else{/*Read in the file and store it in pstr*/
	if (fp == NULL){printf("%s: fatal error: cant open file\n", argv[0]);exit(0);}
	else{
	printf("Reading Data From File\n");  
	fread(pstr, file_size, 1, fp);
	fclose(fp);
	}

}

counter = 0;
counter2 = 0;
counter3 = 0;
FILE *fp2 = fopen("output.bf", "w");

printf("Converting File Data Into BrainF**k Code\n");

while (counter <= file_size){

while(counter2 < pstr[counter3] && counter2 < 127){

fputc('+', fp2);
counter2++;
}

fputc('.', fp2);
fputc('>', fp2);
fputc('\n', fp2);

counter2 = 0;
counter3++;
counter++;
}

fclose(fp2);
free(pstr);

printf("Finished!\n");

return 0;
}
